package org.example.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class DateUtil {
    /**
     * 获取日期的开始、结束时间戳
     * @param dateString yyyy-MM-dd格式String
     * @return [0] startTime时间戳     [1] endTime时间戳
     */
    public static long[] getDayStartAndEndTimestamp(String dateString) {
        LocalDate date = LocalDate.parse(dateString);
        LocalDateTime startDateTime = LocalDateTime.of(date, LocalTime.MIN);
        // 如果是当日endTime就是当前时间
        LocalDateTime endDateTime = date.isEqual(LocalDate.now())
                ? LocalDateTime.now()
                : LocalDateTime.of(date, LocalTime.MAX);
        return new long[]{startDateTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(),
                endDateTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli()};
    }
    // 获取前一天的日期
    public static String getPreviousDay(String dateString) {
        LocalDate date = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate previousDay = date.minusDays(1);
        return previousDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    // 毫秒级时间戳转换为String类型时间
    public static String timestampToString(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(timestamp);
        return sdf.format(date);
    }

    // String类型时间转换为毫秒级时间戳
    public static long stringToTimestamp(String timeStr) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(timeStr);
        return date.getTime();
    }
    // 获取两个时间戳之间相差的天数
    public static int getDaysBetween(long timestamp1, long timestamp2) {
        LocalDateTime dateTime1 = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp1), ZoneOffset.systemDefault());
        LocalDateTime dateTime2 = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp2), ZoneOffset.systemDefault());
        long days = ChronoUnit.DAYS.between(dateTime1, dateTime2);
        System.out.println("ts1:"+timestamp1+" ts2:"+timestamp2+" daysBetween:"+days);
        return (int) days;
    }
    //
    public static long getTimestampMinutesBefore(int minutes){
        long currentTimeMillis = System.currentTimeMillis();
        long minutesInMillis = minutes * 60 * 1000;
        return currentTimeMillis - minutesInMillis;
    }
}
